package com.ra.system;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.BlacklistService;
import com.espirit.eap.manager.SystemDataService;
import com.espirit.eap.manager.TaskSchedulerService;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.ra.util.SmsLog;
import com.ra.util.SmsService;

@Service
public class AttackCheckService {

	@Resource
	private TaskSchedulerService taskSchedulerService;
	
	@Resource
	private GenericService genericService;
	
	@Resource
	private BlacklistService blacklistService;
	
	@Resource
	private SystemDataService systemDataService;
	
	// 每5分钟检测一次
	public void check() {
		// 1. check sms, 需要反馈但未反馈的短信
		if (systemDataService.getValue(SmsService.SYSTEMDATA_AUTO_SMS_VERIFY_CODE, true, false)) {
			String ql = "from " + SmsLog.class.getName() + " a where a.feedback=false and (a.type=? or a.type=? or a.type=? or a.type=?) and a.sendDate>?";
			Calendar now = Calendar.getInstance();
			Date last30Min = DateUtils.addMinutes(now.getTime(), -30);
			int missedSms = genericService.getCount(new QLInfo(ql, true, SmsLog.TYPE_REGISTER, SmsLog.TYPE_RESET_PASSWORD,
					SmsLog.TYPE_BIND_WEIXIN, SmsLog.TYPE_SWITCH_ASSIST, last30Min), false);
			if (missedSms > 10) {
				systemDataService.setValue(SmsService.SYSTEMDATA_USE_SMS_VERIFY_CODE, "true", true);
			} else {
				systemDataService.setValue(SmsService.SYSTEMDATA_USE_SMS_VERIFY_CODE, "false", true);
			}
		}
		
		// 2. 每小时的访问量为本周均值的5倍
		
		
		// 3. 同一ip, 短期发送了大量的请求
		
		// 4. 
		
		taskSchedulerService.updateTaskSchedulerRunTime(this.getClass(), "check");
	}
}
